package com.zhihuishu.micro.course.openapi.exam.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

import com.zhihuishu.micro.course.dto.ChapterDto;
import com.zhihuishu.micro.course.dto.CourseDto;
import com.zhihuishu.micro.course.helper.RedisKeyHelper;
import com.zhihuishu.micro.course.openapi.exam.CourseOpenService;
import com.zhihuishu.micro.course.openapi.exam.dto.ChapterWebDto;
import com.zhihuishu.micro.course.openapi.exam.dto.CourseOpenDto;
import com.zhihuishu.micro.course.service.ChapterService;
import com.zhihuishu.micro.course.service.CourseService;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;
import com.zhihuishu.toolkit.jedis.JedisHelper.Handler;
import com.zhihuishu.toolkit.jedis.template.JedisExecutor;

@Service("examCourseOpenService")
public class CourseOpenServiceImpl implements CourseOpenService {

    @Resource
    private JedisExecutor jedisExecutor;
    @Resource
    private CourseService courseService;

    @Resource
    private ChapterService chapterService;

  

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public RemoteResult<ChapterWebDto> queryChapter(final int chapterId) {
        RemoteResult<ChapterWebDto> result = new RemoteResult<ChapterWebDto>();
        ChapterDto dto = chapterService.get(chapterId);
        if (dto != null) {
            final ChapterWebDto cwd = new ChapterWebDto();
            cwd.setId(dto.getId());
            cwd.setLimitDay(dto.getLimitDay());
            cwd.setName(dto.getName());
            cwd.setRank(dto.getRank());
            result.setResult(cwd);
        }
        return result;
    }

    @Override
    public RemoteResult<Integer> queryCourseLimitDays(final long courseId) {
        RemoteResult<Integer> result = new RemoteResult<Integer>();
        String limitDay = courseService.getByField(courseId, "limitDay");
        if (StringUtils.isNotBlank(limitDay)) {
            result.setResult(NumberUtils.toInt(limitDay));
        }
        return result;
    }

    @Override
    public RemoteResult<Integer> queryChaptersLimitDays(final long courseId, final Integer chapterId) {
        RemoteResult<Integer> result = new RemoteResult<Integer>();
        List<ChapterDto> list = chapterService.list(courseId);
        if (!CollectionUtils.isEmpty(list)) {
            int days = 0;
            for (ChapterDto dto : list) {
                if (dto.getLimitDay() != null)
                    days += dto.getLimitDay();
                // 循环到指定章ID时，结束循环
                if (chapterId != null && dto.getId().equals(chapterId))
                    break;
            }
            result.setResult(days);
        } else {
            result.setResult(0);
        }
        return result;
    }

    @Override
    public RemoteResult<String> queryCourseName(final long courseId) {
        RemoteResult<String> result = new RemoteResult<String>();
        result.setResult(courseService.getCourseName(courseId));
        return result;
    }

    @Override
    public RemoteResult<Void> delProgressByCourseId(final Long courseId) throws RemoteException {
        RemoteResult<Void> r = new RemoteResult<Void>();
        if (courseId != null) {
            /*Jedis jedis = null;
            try {
                jedis = jedisPool.getResource();
                Pipeline pip = jedis.pipelined();
                String progressInfoKey = "";
                progressInfoKey = RedisKeyHelper.getProgressInfoKey(courseId);
                pip.del(progressInfoKey);
            } finally {
                JedisHelper.closeQuietly(jedis);
            }*/
            jedisExecutor.execute(new Handler() {
                
                @Override
                public void handle(Jedis jedis) {
                    Pipeline pip = jedis.pipelined();
                    String progressInfoKey = "";
                    progressInfoKey = RedisKeyHelper.getProgressInfoKey(courseId);
                    pip.del(progressInfoKey);
                    
                }
            });
        }
        return r;
    }

    @Override
    public RemoteResult<Integer> queryCourseTypeByCourseId(long courseId) {
        RemoteResult<Integer> remoteResult = new RemoteResult<Integer>();
        try {
            Assert.isTrue(courseId>0, "参数不合法");
            Integer type=courseService.queryCourseTypeByCourseId(courseId);
            remoteResult.setResult(type);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("查询课程类型出错,参数为{}",courseId,e);
        }
        return remoteResult;

    }

    @Override
    public RemoteResult<CourseOpenDto> queryCourseInfoByCourseId(long courseId) {
        RemoteResult<CourseOpenDto> remoteResult=new RemoteResult<CourseOpenDto>();
        try {
            Assert.isTrue(courseId>0, "参数不合法");
            CourseDto courseDto = courseService.get(courseId);
            CourseOpenDto courseOpenDto = BeanHelper.transTo(courseDto, CourseOpenDto.class);
            remoteResult.setResult(courseOpenDto);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("查询课程信息出错,课程id为{}",courseId,e);
        }
        return remoteResult;
       
    }

}
